package com.bsoft.rpc.basic.dynamicProxy.cglib.basic;

import com.alibaba.fastjson.JSON;
import com.bsoft.rpc.basic.dynamicProxy.OrgInfo;
import lombok.extern.slf4j.Slf4j;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

@Slf4j
public class CGlibProxyInterceptor implements MethodInterceptor {

    /**
     * 拦截方法
     *
     * @param o 拦截目标对象
     * @param method 拦截目标方法
     * @param objects 方法入参
     * @param methodProxy 代理方法
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        if (objects != null && objects.length > 0) {
            log.info("拿到入参 type：{},value:{}", objects[0].getClass().getName(), objects[0]);
            log.info("------------>前置增强<------------");
            Object result = methodProxy.invokeSuper(o, objects);
            log.info("------------>后置增强<------------");
            return result;
        }
        return method.invoke(o,objects);
    }

    public static void main(String[] args) {

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(OrgService.class);
        enhancer.setCallback(new CGlibProxyInterceptor());

        OrgService orgService = (OrgService) enhancer.create();
        OrgInfo orgInfo = orgService.getById("aaa");
        System.out.println(JSON.toJSONString(orgInfo));

    }
}
